package com.example.datagramsocket

import android.widget.Toast
import com.binyouwei.udp_lib.factory.AnycastFactory
import com.binyouwei.udp_lib.factory.BroadcastFactory
import com.example.datagramsocket.base.BaseActivity
import com.example.datagramsocket.databinding.ActivityAnycastBinding

/**
 * 任播
 */
class AnycastActivity : BaseActivity<ActivityAnycastBinding>() {
    val mFactory: AnycastFactory by lazy { AnycastFactory() }

    override fun initView() {
        mBinding.apply {
            mFactory.initUdp()

            initBtn.setOnClickListener {
                mFactory.onReceiveMessageListener("任播接收数据报不需要IP") { msg ->
                    this@AnycastActivity.runOnUiThread {
                        receiveMessage.text = msg
                    }
                }
            }
            sendBtn.setOnClickListener {
                if (sendMessage.text.toString().isEmpty()) {
                    Toast.makeText(this@AnycastActivity, "消息不能为空", Toast.LENGTH_SHORT)
                        .show()
                    return@setOnClickListener
                }
                // 任播的地址是239.255.255.255
                mFactory.sendMessage(targetIp.text.toString(), sendMessage.text.toString())
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mFactory.destroyUdp()
    }
}